import {
  Component, OnChanges, OnInit, Input,
  SimpleChanges, Output, EventEmitter,
  ViewChildren, QueryList, ElementRef
} from '@angular/core';
import {Song} from '../../../../../data-types/common.types';
import {ScrollComponent} from '../scroll/scroll.component';

@Component({
  selector: 'app-player-panel',
  templateUrl: './player-panel.component.html',
  styleUrls: ['./player-panel.component.less']
})
export class PlayerPanelComponent implements OnInit, OnChanges {

  @Input() songList: Array<Song>;

  @Input() currentSong: Song;

  @Input() currentIndex: number;

  @Input() show: boolean;

  @Output() closeEvent = new EventEmitter<void>();

  @Output() changeSongEvent = new EventEmitter<Song>();

  @ViewChildren(ScrollComponent) private playListScroll: QueryList<ScrollComponent>;

  public scrollY: number;

  constructor() {
    this.show = false;
  }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.songList) {
      console.log('changes songList', this.songList);
    }

    if (changes.currentSong) {
      if (this.currentSong) {
        if (this.show) {
          this.scrollToCurrent();
        }
      }
    }

    if (changes.show) {
      if (!changes.show.firstChange && this.show) {
        this.playListScroll.first.refreshScroll();
        if (this.currentSong) {
          setTimeout(() => {
            this.scrollToCurrent();
          }, 80);
        }
      }
    }
  }

  public onPanelClose() {
    this.closeEvent.emit();
  }

  public songListItemClick(song: Song) {
    this.changeSongEvent.emit(song);
  }

  private scrollToCurrent() {
    const songListRefs = this.playListScroll.first.wrapRef.nativeElement.querySelectorAll('ul li');
    if (songListRefs.length > 0) {
      const currentLi = songListRefs[this.currentIndex || 0] as HTMLElement;
      const offsetHeight = currentLi.offsetHeight;
      const offsetTop = currentLi.offsetTop;
      if (offsetTop - Math.abs(this.scrollY) > offsetHeight * 5 || (offsetTop < Math.abs(this.scrollY))) {
        this.playListScroll.first.scrollToElement(currentLi, 300, false, false);
      }
    }
  }

}
